var app = angular.module("editApp", []),
//	articleId = UI.getParameterByName('articleId'),
	id = UI.getParameterByName('id'),
	parid = UI.getParameterByName('parId'),
	optEdit;

var timeout_json=function(data,$window){ 
	if (data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if (ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try{
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				}catch(e){ 
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}
/**
 * 在AngularJS的页面中，如果使用数据绑定生成链接，默认会添加'unsafe:'标识，
 * 在模块配置中，增加参数（$compileProvider）修改默认支持的协议javascript。
 */
app.config(function($httpProvider, $compileProvider) {
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data) {
        /**
         * The workhorse; converts an object to x-www-form-urlencoded serialization.
         * @param {Object} obj
         * @return {String}
         */
        var param = function(obj) {
            var query = '';
            var name, value, fullSubName, subName, subValue, innerObj, i;
 
            for (name in obj) {
                value = obj[name];
 
                if (value instanceof Array) {
                    for (i = 0; i < value.length; ++i) {
                        subValue = value[i];
                        fullSubName = name + '[' + i + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value instanceof Object) {
                    for (subName in value) {
                        subValue = value[subName];
                        fullSubName = name + '[' + subName + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                } else if (value !== undefined && value !== null) {
                    query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                }
            }
            return query.length ? query.substr(0, query.length - 1) : query;
        };
        return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
    }];
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|javascript):/);
});

app.controller('editCtrl', function($scope, $http,$window,$timeout) {
	var vm = $scope.vm = {
		id: id,
		title:'',
		seedType:'',
		url:'',
		content:'',
		source:'',
		author:'',
		publishTime:'',
		weixinId:''
	};
	$scope.addSel = true;
	if(id!=null){
		optEdit = 1;
		document.title = '编辑信息';
		$scope.addSel = false;
		angular.element(window).bind('load', function() {
			//列表页面点击操作--修改--修改接口
			$http.get(basePath + 'FinalDb/findId.do?id=' + id + '&vtimes=' + new Date().getTime()).success(function(data) {
				//console.log(data)
				var j=timeout_json(data,$window);
				if(j==false){ 
					return false;
				}
				var editor="";
		    	window.htmlContent=data.returnData.content;
		    	$scope.vm = data.returnData;
		    	$("#myEditor").val(window.htmlContent);
		    	window.editor= KindEditor.create("#myEditor", {
			            cssPath : basePath +'js/kindeditor-4.1.10/plugins/code/prettify.css',
	//		            uploadJson : '<%=basePath%>uloadondown.action',//上传的请求
	//		            fileManagerJson : '<%=basePath%>fmanage.action',
			            allowFileManager : true,
			            height:"300px",
			            resizeType:1  /*说明resizeType 2或1或0，2时可以拖动改变宽度和高度，1时只能改变高度，0时不能拖动。  数据类型: Int  默认值: 2 */,
			        });			
				if($scope.vm.seedType=="News"){
					$("#seedTypeId").val("新闻");
				}else if($scope.vm.seedType=="WeiXin"){
					$("#seedTypeId").val("微信");
				}else if($scope.vm.seedType=="Micro"){
					$("#seedTypeId").val("微博");
				}else if($scope.vm.seedType=="BBS"){
					$("#seedTypeId").val("论坛");
				}
				if($scope.vm.seedType=="WeiXin"){
					$scope.authorOrWeixin = false;
					$("#authorBase").attr("readonly","readonly");
				}else{
					$scope.authorOrWeixin = true;
					$("#authorBase").removeAttr("readonly");
				}
			});
		});
	}else{
		optEdit = 0;
		document.title = '新增信息';
		//如何选择渠道为微信，那么将‘作者’改为‘微信ID’
		$scope.authorOrWeixin = true;
		$scope.thChange = function(e){
			if(e=="w"){
				$scope.authorOrWeixin = false;
			}else{
				$scope.authorOrWeixin = true;
			}
		};
		$scope.addSel = true;
    	window.editor= KindEditor.create("#myEditor", {
            cssPath : basePath +'js/kindeditor-4.1.10/plugins/code/prettify.css',
//		            uploadJson : '<%=basePath%>uloadondown.action',//上传的请求
//		            fileManagerJson : '<%=basePath%>fmanage.action',
            allowFileManager : true,
            height:"300px",
            resizeType:1  /*说明resizeType 2或1或0，2时可以拖动改变宽度和高度，1时只能改变高度，0时不能拖动。  数据类型: Int  默认值: 2 */,
        });	
	}
	
	$scope.toSource = function(){
		if($scope.vm.url!=""){
			$scope.toSourceUrl = $scope.vm.url;
		}else{
			$scope.toSourceUrl = 'javascript:void(0);';
		}
	}
	
	var avoidDup = true;
	$scope.domAjax = function(e) {
//		var data = $scope.content;
		if (e === "release") {
			if(avoidDup==false){
				return false;
			}
			if($scope.vm.title!=undefined){vm.title=$scope.vm.title;}
			if(optEdit==0){
				vm.seedType=$("#artcleTE").val();
			}
			if($scope.vm.url!=undefined){vm.url=$scope.vm.url;}
			if($scope.vm.seedType!=undefined){
				if($("#seedTypeId").val()=="新闻"){
					$scope.vm.seedType="News";
				}else if($("#seedTypeId").val()=="微信"){
					$scope.vm.seedType="WeiXin";
				}else if($("#seedTypeId").val()=="微博"){
					$scope.vm.seedType="Micro";
				}else if($("#seedTypeId").val()=="论坛"){
					$scope.vm.seedType="BBS";
				}
				vm.seedType=$scope.vm.seedType;
			}
			if($scope.vm.author!=undefined){vm.author = $scope.vm.author;}
			if($scope.vm.publishTime!=undefined){vm.publishTime = $("#publishTimeBase").val();}
			if($scope.vm.source!=undefined){vm.source = $scope.vm.source;}
			//html()包括标签的textarea内容，text()为textarea的纯文本内容
			vm.content=editor.text();
			//editor已定义为全局变量window。editor，同步数据可以直接取得textarea的value
			editor.sync();

//			if(vm.reprintNumber!=undefined){
//				if(isNaN(vm.reprintNumber)){layer.msg('转载量请输入数字！',1, -1);return false}
//			}
//			vm.digest=$scope.vmm.myDigest;			
//			if(vm.digest!=undefined){
//				vm.digest = vm.digest.replace(/<\/?.+?>/g,"").replace(/&nbsp;/g,"");
//				if(vm.digest.length>200){layer.msg('摘要不能超过200字！',1, -1);return false}
//			} 

			if(vm.title!=undefined){
				if(vm.title.length<=0){layer.msg('标题不能为空！',1, -1);return false}
				else if(vm.title.length>50){layer.msg('标题限于50字符以内！',1, -1);return false}
			}
			if(vm.author!=undefined){
				if(vm.author.length>50){layer.msg('作者限于50字符以内！',1, -1);return false}
				if($("#artcleTE").val()=="WeiXin"){
					vm.weixinId = vm.author;
					if(vm.author.length<=0){layer.msg('微信ID不能为空！',1, -1);return false}
				}
			}
			if(vm.publishTime!=undefined){
				if(vm.publishTime.length<=0){layer.msg('发布时间不能为空！',1, -1);return false}
			}
			if(vm.source!=undefined){
				if(vm.source.length<=0){layer.msg('首发媒体不能为空！',1, -1);return false}
				else if(vm.source.length>50){layer.msg('首发媒体限于50字符以内！',1, -1);return false}
			}
			if(vm.url!=undefined){
				if(vm.url.length<=0){layer.msg('原文链接不能为空！',1, -1);return false}
				else if(vm.url.length>1000){layer.msg('原文链接限于1000字符以内！',1, -1);return false}
			}
			//验证url地址
			var strReg = "^((https|http)?://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?";
			var re = new RegExp(strReg);
			if(!re.test($.trim(vm.url))) {
				layer.msg("请输入以'http://'或'https://'开头的有效网址！",3,-1);
				return false;
			}
			if(vm.content!=undefined){
				if(vm.content.length<=0){layer.msg('正文内容不能为空！',1, -1);return false}
			}	
			var urls = ['FinalDb/insert.do', 'FinalDb/update.do'];
			avoidDup =false;
			$http.post(basePath + urls[optEdit], vm).success(function(data) {
				var j=timeout_json(data,$window);
				if(j==false){ 
					return false;
				}
				if(data.returnCode==10000){
					layer.msg("正在运行，请稍后...", 3, -1);
					setTimeout(function(){
						layer.msg(data.returnMessage, 1, 10);
						if(optEdit==1){
							setTimeout(function(){
								window.parent.$(".dtab").find('#jsgo a.cur').trigger('click');
								window.parent.layer.closeAll();
							},1000);
						}else{
							setTimeout(function(){
								parent.location.reload();
							},1000);
						}
					},3000);
				}else{ 
					layer.msg(data.returnMessage, 2, -1);
					avoidDup =true;
					return false;
				}
			});
		}
	};
});

$(function() {
	var pc_time = UI.getTimes();
	$("#publishTimeBase").val(pc_time.end_ymd_hms);
	laydate.skin('molv');
	$('.ui_select').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t'),
			_c = _.find('.ui_s_bk'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
			$("#artcleTE").val($(this).attr("type"));
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});

	$('.ui_select').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk'),
			di = 27;
		_.focus();
		e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
			sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t').blur();
		}
		return false;
	});
	
//	$("#myDigest").css({"min-height":"60px","width":"1040px","height":"auto","margin":"4px 8px","vertical-align":"middle","line-height":"18px"});
	$("#myEditor").css({"width":"100%","height":"auto"}); 	
});
